#pragma  once 
#include"Reactor.hpp"
#include<vector>
#include<unistd.h>
#include"Util.hpp"
//
#define ONCE_SIZE 128
//1 本轮读取全部完成
//-1 读取出错
//0 对端关闭连接

static int RecverCore(int sock,string& inbuffer)
{
  while(true)
  {
    char buffer[ONCE_SIZE];
    ssize_t s = recv(sock,buffer,ONCE_SIZE-1,0);
    if(s>0)
    {
      //读取成功
      buffer[s] = '\0';
      inbuffer+=buffer;
    }
    else if(s<0)
    {
      if(errno==EINTR)//中断去做别的事情了，等一下
      {
        continue;
      }
      //1.读完底层没数据了
      if(errno==EAGAIN||errno==EWOULDBLOCK)
      {
        return 1;//success
      }
      //真的出错了
      else 
      {
        return -1;
      }
    }
    else //s==0对端连接关闭了
    {
      return 0;
    }
  }
}



int recver(Event* evp)
{
  //1.真正读取
  int result =  RecverCore(evp->sock,evp->inbuffer);
  if(result<=0)
  {
    //差错处理
    if(evp->errer) evp->errer(evp);
    return -1;
  }
  //2.分包
  vector<string> tokens;

  SplitSegment(evp->inbuffer,&tokens,"X");
  //3.反序列化，针对一个报文，
  for(auto& seg:tokens)
  {
    string data1,data2;

    if(Deserialize(seg,&data1,&data2))//反序列化
    {
      int x =atoi(data1.c_str()); 
      int y = atoi(data2.c_str());
      int z = x+y;

      //4.业务逻辑--得到结果
      //5.构建响应--添加到evp->outbuffer
      string res = data1;
      res+="+";
      res+=data2;
      res+="=";
      res+=to_string(z);
      res+="X"; 
      evp->outbuffer+=res;//   
    }
  }
  //6.尝试直接间接进行发送 
  if(!((evp->outbuffer).empty()))
  {
    evp->R->EnableRW(evp->sock,true,true);
  }
}

//1 发完了
//0. 数据没发完，不能发了
//-1。 发送失败
int SenderCore(int sock, string &outbuffer)
{
  while(1)
  {
    int total = 0;//本轮累计发送的数据量
    const char *start = outbuffer.c_str();
    int size = outbuffer.size();
    ssize_t curr = send(sock,start+total,size-total,0);
    if(curr>0)
    {
      total+=curr;
      if(total==size)
      {
        // data send finish
        outbuffer.clear();
        return 1;
      }
    }
    else 
    {
      if(errno==EINTR) continue;
      if(errno==EAGAIN||errno==EWOULDBLOCK)
      {
        outbuffer.erase(0,total);
        return 0;
      }
      return -1;
    }
  }
}

int sender(Event* evp)
{
  int res =  SenderCore(evp->sock,evp->outbuffer);
  if(res==1)
  {
    evp->R->EnableRW(evp->sock,true,false);

  }
  else if(res==0)
  {
    // 
    evp->R->EnableRW(evp->sock,true,true);
  }

  else 
  {
    if(evp->errer)
    {
      evp->errer(evp);
    }
  }


}

int errorer(Event* evp)
{
  cout<<"Error been called!!"<<endl;
  evp->R->DeleteEvent(evp);

}

